<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolBar" style="float:left;padding-top: 10px;padding-left: 50px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-form-item prop="name">
          <el-input v-model="filters.name" placeholder="名称" style="width: 10em"></el-input>
        </el-form-item>
        <el-form-item prop="innerCode">
          <el-input v-model="filters.innerCode" placeholder="产品编码" style="width: 10em"></el-input>
        </el-form-item>
        <el-form-item prop="supplierId">
          <el-select v-model="filters.supplierId" filterable clearable placeholder="供应商" style="width: 10em">
            <el-option v-for="item in suppliers"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-search"
                     :label="$t('action.search')"
                     perms="supply:product:view"
                     @click="findPage"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-refresh"
                     :label="$t('action.reset')"
                     perms="supply:product:view"
                     @click="reset"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-plus"
                     :label="$t('action.add')"
                     perms="supply:product:add"
                     @click="showAdd"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-filter"
                     label="列显示"
                     perms="sale:order:view"
                     @click="displayFilterColumnDialog"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-file-excel-o"
                     label="导出"
                     perms="sale:order:view"
                     @click="displayFilterColumnDialog"/>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog ref="tableColumnFilterDialog"
                                  :columns="columns"
                                  @handleFilterColumns="handleFilterColumns">
      </table-column-filter-dialog>
    </div>

    <!--表格内容栏-->
    <!--不设置删除按钮 perms-delete="sale:goods:delete"-->
    <kt-table perms-edit="supply:product:edit" :data="pageResult" :columns="filterColumns" @findPage="findPage"
              @handleEdit="showEdit"></kt-table>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="35%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="100px" :rules="dataFormRules" ref="dataForm" :size="size"
               label-position="right">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="false"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="dataForm.name" maxlength="50" auto-complete="false"></el-input>
        </el-form-item>
        <el-form-item label="产品编码" prop="innerCode">
          <el-input v-model="dataForm.innerCode" :disabled="!operation" auto-complete="false"></el-input>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierIds">
          <el-select v-model="dataForm.supplierIds"
                     :clearable="true"
                     :filterable="true"
                     multiple
                     placeholder="选择供应商"
                     auto-complete="false"
                     style="width: 100%">
            <el-option v-for="item in suppliers"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
              <span style="float:left">{{item.name}} : {{item.mainProducts}}</span>
              <!-- <span style="float:right;color: crimson;font-size: 13px">主营产品: {{item.mainProducts}}</span>-->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购成本(￥)" prop="purchaseCost">
          <el-input-number v-model="dataForm.purchaseCost"
                           auto-complete="false"
                           size="large"
                           :precision="2"
                           :min='0.00'
                           :step='0.50'
                           align="left">
          </el-input-number>
        </el-form-item>
        <el-form-item label="包装成本(￥)" prop="packCost">
          <el-input-number v-model="dataForm.packCost"
                           auto-complete="false"
                           size="large"
                           :precision="2"
                           :min='0.00'
                           :step='0.10'>
          </el-input-number>
        </el-form-item>
        <el-form-item label="长度(CM)" prop="length">
          <el-input-number v-model="dataForm.length"
                           auto-complete="false"
                           size="large"
                           :min="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="宽度(CM)" prop="width">
          <el-input-number v-model="dataForm.width"
                           auto-complete="false"
                           size="large"
                           :min="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="高度(CM)" prop="height">
          <el-input-number v-model="dataForm.height"
                           auto-complete="false"
                           size="large"
                           :min="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="商品重量(g)" prop="productWeight">
          <el-input-number v-model="dataForm.productWeight"
                           auto-complete="false"
                           size="large"
                           :min="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="体积重量(g)" prop="volumeWeight">
          <el-input-number v-model="dataForm.volumeWeight"
                           auto-complete="false"
                           size="large"
                           :min="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="上传图片" prop="showUrl">
          <el-upload :class="{hide:hideUpload}"
                     action=""
                     :limit="1"
                     :before-upload="beforeUpload"
                     :http-request="handleUpload"
                     :on-remove="handleRemove"
                     :on-change="handleChange"
                     list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button :size="size" @click.native="dialogVisible=false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" type="primary" :loading="editLoading" @click.native="submitForm">
          {{$t('action.submit')}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import KtTable from '../core/KtTable'
  import KtButton from '../core/KtButton'
  import TableColumnFilterDialog from '../core/TableColumnFilterDialog'

  export default {
    name: "Product",
    components: {
      KtTable,
      KtButton,
      TableColumnFilterDialog
    },
    data() {
      return {
        size: 'small',
        filters: {
          name: '',
          innerCode: '',
          supplierId: ''
        },
        columns: [],//初始表格列显示字段
        filterColumns: [],//列显示过滤字段
        pageRequest: {},
        pageResult: {},
        operation: false,//true新增 false编辑
        dialogVisible: false,//新增编辑界面是否显示
        editLoading: false,
        hideUpload: false,//隐藏上传添加按钮
        //新增或编辑页面
        dataForm: {
          id: 0,
          name: '',
          innerCode: '',
          showUrl: '',
          purchaseCost: 0.00,
          packCost: 0.10,
          length: 0,
          width: 0,
          height: 0,
          productWeight: 0,
          volumeWeight: 0,
          supplierIds: [2123],
          remark: ''
        },
        dataFormRules: {
          name: [
            {required: true, message: '请定义名称', trigger: 'blur'}
          ],
          supplierIds: [
            {required: true, message: '请选择供应商', trigger: 'blur'}
          ],
          innerCode: [
            {required: true, message: '请定义产品编码', trigger: 'blur'}
          ]
        },
        //供应商信息
        suppliers: []
      }
    },
    methods: {
      // 处理表格列过滤显示
      initColumns() {
        this.columns = [
          {prop: "id", label: "ID", minWidth: 50},
          {prop: "name", label: "名称", showOverflow: true, minWidth: 150},
          {prop: "innerCode", label: "产品编码", minWidth: 100},
          {prop: "showUrl", label: "缩略图", minWidth: 100, picture: true},
          {prop: "purchaseCost", label: "采购成本(￥)", formatter: true, sortable: true, minWidth: 120},
          {prop: "packCost", label: "包装成本(￥)", formatter: true, minWidth: 100},
          {prop: "length", label: "长度(CM)", minWidth: 80},
          {prop: "width", label: "宽度(CM)", minWidth: 80},
          {prop: "height", label: "高度(CM)", minWidth: 80},
          {prop: "productWeight", label: "商品重量(g)", minWidth: 80},
          {prop: "volumeWeight", label: "体积重量(g)", minWidth: 80},
          {prop: "supplierNames", label: "供应商", showOverflow: true, minWidth: 200},
        ];
        this.filterColumns = JSON.parse(JSON.stringify(this.columns));
      },
      //处理表格列过滤显示
      displayFilterColumnDialog() {
        this.$refs.tableColumnFilterDialog.setDialogVisible(true);
      },
      // 处理表格列过滤显示
      handleFilterColumns(data) {
        this.filterColumns = data.filterColumns;
        this.$refs.tableColumnFilterDialog.setDialogVisible(false);
      },
      //获取分页数据
      findPage(data) {
        if ((data !== null && typeof data !== 'undefined') && typeof data.pageRequest !== 'undefined') {
          this.pageRequest = data.pageRequest;
        }
        this.pageRequest.params = {
          name: this.filters.name,
          innerCode: this.filters.innerCode,
          supplierIds: this.filters.supplierId
        };
        this.$api.product.findPage(this.pageRequest).then((res) => {
          if (res.code === 200) {
            this.pageResult = res.data;
            this.convertSupplyName(this.pageResult);
          }
        }).then((data !== null && typeof data !== 'undefined') ? data.callback : '');
      },
      //平台名称转换
      convertSupplyName(pageResult) {
        let productList = pageResult.content;
        productList.forEach(p => {
          let supplierIds = [];
          if (p.supplierIds !== null || p.supplierIds !== '') {
            supplierIds = p.supplierIds;
          }
          let supplierNames = [];
          for (let i = 0, len = supplierIds.length; i < len; i++) {
            this.suppliers.forEach(s => {
              if (s.id === supplierIds[i]) {
                if (i < len - 1) {
                  supplierNames.push(s.name + ', ');
                } else {
                  supplierNames.push(s.name);
                }
              }
            })
          }
          p.supplierNames = supplierNames;
        })
      },
      //显示新增界面
      showAdd() {
        this.dialogVisible = true;
        this.operation = true;
      },
      //显示编辑界面
      showEdit(params) {
        this.dialogVisible = true;
        this.operation = false;
        this.dataForm = Object.assign({}, params.row);
      },
      //编辑
      submitForm() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗?', '提示', {}).then(() => {
              this.editLoading = true;
              this.$api.product.save(this.dataForm).then((res) => {
                this.editLoading = false;
                if (res.code === 200) {
                  this.$message({message: '操作成功', type: 'success'});
                  this.dialogVisible = false;
                  this.$refs['dataForm'].resetFields();
                } else {
                  this.$message({message: res.message, type: 'error'});
                }
                this.findPage();
              })
            });
          }
        })
      },
      //获取供应商
      findSuppliers() {
        this.$api.supplier.findAll().then((res) => {
          this.suppliers = res.data;
        })
      },
      reset() {
        this.$refs['filters'].resetFields();
        this.findPage();
      },
      //上传文件前校验
      beforeUpload(file) {
        let imgType = file.type;
        //校验格式
        if (imgType === 'image/jpg'
          || imgType === 'image/jpeg'
          || imgType === 'image/png'
          || imgType === 'image/PNG') {
          console.log(imgType);
        } else {
          this.$message.error(`图片格式仅支持PNG|JPG|JPEG`);
          return false;
        }
        //校验大小
        let isLt1M = file.size / 1024 / 1024 < 1;
        if (!isLt1M) {
          this.$message.error('上传图片大小不能超过1MB!');
        }
        return isLt1M;
      },
      //执行上传逻辑
      handleUpload(params) {
        let formData = new FormData();
        formData.append('file', params.file);
        formData.append('module', 'product');
        this.$api.file.upload(formData).then((res) => {
          if (res.code === 200) {
            this.dataForm.showUrl = res.data;
          } else {
            this.$message({message: res.message, type: 'error'});
          }
        })
      },
      //删除图片
      handleRemove(file, fileList) {
        if (this.dataForm.showUrl !== null) {
          this.$api.file.deleteFile({fileUrl: this.dataForm.showUrl}).then((res) => {
            if (res.code === 200) {
              this.dataForm.showUrl = '';
            }
          })
        }
        this.hideUpload = fileList.length >= 1;
      },
      //改变显示
      handleChange(file, fileList) {
        this.hideUpload = fileList.length >= 1;
      }
    },
    mounted() {
      this.initColumns();
      this.findSuppliers();
    }
  }
</script>

<style>
  .hide .el-upload--picture-card {
    display: none;
  }
</style>
